import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../model/player_record.dart';
import '../channel/channel.dart';
import '../sdk_service.dart';

class CureRecordApi extends GetConnect {
  CureRecordApi();

  final path = "cloud-digital-healing/sdkScheme/saveUserSchemeRecord";

  Future upload(PlayerRecord record) async {
    final sdk = Get.find<SDKService>();
    final hostURL = sdk.host;
    final absoluteURL = "$hostURL/$path";

    Map<String, dynamic> param = {};
    param["sourceFrom"] = "1";
    param["schemeId"] = record.cureID.toString();
    param["endTime"] = record.endAt;
    param["seconds"] = record.seconds.toString();
    param["startTime"] = record.startAt.toString();
    param["userId"] = sdk.uuid;
    param["channelId"] = Get.find<ChannelService>().channelID;

    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    param["appId"] = packageInfo.packageName;

    debugPrint("upload begin: ${param}");

    final resp = await get(absoluteURL, query: param);

    final json = resp.body;
    debugPrint("upload end: ${json}");

    final code = json["code"];
    if (code != 1) {
      return Future.error(json["msg"]);
    }
  }
}

class CurePlayMemoService {
  final container = "CurePlayMemoService";
  late GetStorage _box;

  CurePlayMemoService() {
    _box = GetStorage(container);
  }

  Future setUp() async {
    await GetStorage.init(container);
  }

  Future saveRecord(PlayerRecord record) async {
    final key = "${record.cureID}-${record.startAt}";
    await _box.write(key, record.toJson());
  }

  Future sync() async {
    final uploader = CureRecordApi();
    final keys = _box.getKeys();
    List<String> succeed = [];
    for (var e in keys) {
      debugPrint("key: ${e}");
      final json = _box.read(e);
      try {
        final r = PlayerRecord.fromJson(json);
        await uploader.upload(r);
        succeed.add(e);
      } catch (e) {
        debugPrint(e.toString());
      }
    }
    try {
      for (var e in succeed) {
        await _box.remove(e);
      }
    } catch (e) {
      debugPrint(e.toString());
    }
  }
}
